package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.StorageRecord;
import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.service.StorageRecordService;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.utils.Page;
import io.micrometer.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/storageRecord")
public class StorageRecordController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(StorageRecordController.class);

    @Autowired
    private StorageRecordService storageRecordService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    @Qualifier("toLocalUploadService")
    private UploadService uploadService;    // 上传文件服务

    @RequestMapping("/page")
    public String page(Model model, StorageRecord condition,
                       @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {

        Page<StorageRecord> page = null;
        try {
            page = storageRecordService.getPage(condition, pageNo, pageSize);
            List<Supplier> supplierList = supplierService.findAll();
            model.addAttribute("pageInfo", page);
            model.addAttribute("supplierList", supplierList);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            logger.error("StorageRecordController中的page方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/page";
    }

    @GetMapping("/save")
    public String toSave(Model model) {
        List<Supplier> supplierList = null;
        try {
            supplierList = supplierService.findAll();
            model.addAttribute("supplierList", supplierList);
            model.addAttribute("storageRecord", new StorageRecord());
        }catch (Exception e){
            logger.error("StorageRecordController中的toSave方法执行错误", e);
            throw new RuntimeException(e);
        }

        return "storageRecord/save";
    }

    // 检查账号是否存在
    @ResponseBody
    @GetMapping("/srCodeExist")
    public String srCodeExist(@RequestParam("srCode") String srCode) {
        logger.info("检查账号是否存在：{}", srCode);
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(srCode)){
            resultMap.put("exist", 0);
        }else {
            try {
                StorageRecord storageRecord = storageRecordService.getByAccount(srCode);
                if (storageRecord != null) {
                    //账号已存在
                    resultMap.put("exist", 1);
                } else {
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                resultMap.put("error", "验证账号时发生错误");
                logger.error("验证账号出错", e);
            }
        }
        return JSON.toJSONString(resultMap);
    }

    // 新增
    @PostMapping("/save")
    public String save(@ModelAttribute StorageRecord storageRecord, Model model) throws Exception {
        try {
            logger.info("接收到的StorageRecord数据: {}", storageRecord);

            if (storageRecord.getId() == null) {
                // 新增时创建时间
                storageRecord.setCreatedTime(new Date());
                logger.info("执行新增操作");
            } else {
                logger.info("执行修改操作，ID: {}", storageRecord.getId());
            }

            // 修改后更新时间
            storageRecord.setUpdatedTime(new Date());

            boolean ok = storageRecordService.upInsert(storageRecord);
            if (ok){
                return redirect("/main/storageRecord/page");
            }
        } catch (Exception e){
            logger.error("执行StorageRecordController.save()方法出现异常", e);
            model.addAttribute("error", "保存失败: " + e.getMessage());
            // 回显供应商列表
            model.addAttribute("supplierList", supplierService.findAll());
            return "storageRecord/save";
        }
        return "storageRecord/save";
    }

    //查询
    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model){
        StorageRecord storageRecord = null;
        try {
            storageRecord = storageRecordService.getById(id);
            model.addAttribute("storageRecord", storageRecord);
        } catch (Exception e) {
            logger.error("StorageRecordController中的view方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/view";
    }

    // 修改
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        StorageRecord storageRecord = null;
        List<Supplier> supplierList = null;
        try {
            storageRecord = storageRecordService.getById(id);
            supplierList = supplierService.findAll();
            model.addAttribute("supplierList", supplierList);
            model.addAttribute("storageRecord", storageRecord);
        } catch (Exception e) {
            logger.error("StorageRecordController中的edit方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Map<String, Object> del(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean ok = storageRecordService.deleteById(id);
            if (ok){
                result.put("code", 200);
                result.put("message", "删除成功");
            }else{
                result.put("code", 500);
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            result.put("error", "删除角色时发生错误");
            result.put("code", 500);
            logger.error("删除角色出错", e);
        }
        return result;
    }
}
